package com.typingtutor.ui.compose;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 自定义输入对话框类
public class CustomInputDialog extends JDialog {
    private JPanel inputPanel;
    private JButton okButton;
    private JButton cancelButton;
    private List<JTextField> textFields;
    private Map<JTextField, Boolean> requiredFields;
    private Map<JTextField, JLabel> errorLabels;
    private boolean isOkPressed;

    public CustomInputDialog(Component parent, String title, List<String> fieldNames, List<Boolean> requiredFlags, Dimension size) {
        super((parent instanceof Frame)? (Frame) parent : findFrameForComponent(parent), title, true);
        textFields = new ArrayList<>();
        requiredFields = new HashMap<>();
        errorLabels = new HashMap<>();
        isOkPressed = false;

        inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;

        // 创建输入框和标签
        for (int i = 0; i < fieldNames.size(); i++) {
            String fieldName = fieldNames.get(i);
            boolean isRequired = requiredFlags.get(i);

            gbc.gridx = 0;
            gbc.gridy = i * 3;
            JLabel label = new JLabel(fieldName + (isRequired? " *" : ""));
            inputPanel.add(label, gbc);

            gbc.gridy = i * 3 + 1;
            JTextField textField = new JTextField();
            inputPanel.add(textField, gbc);
            textFields.add(textField);
            requiredFields.put(textField, isRequired);

            gbc.gridy = i * 3 + 2;
            JLabel errorLabel = new JLabel("该项为必填项", SwingConstants.CENTER);
            errorLabel.setForeground(Color.RED);
            errorLabel.setVisible(false);
            inputPanel.add(errorLabel, gbc);
            errorLabels.put(textField, errorLabel);

            textField.addFocusListener(new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent e) {
                    if (isRequired && textField.getText().trim().isEmpty()) {
                        showError(textField);
                    } else {
                        hideError(textField);
                    }
                }

                @Override
                public void focusGained(FocusEvent e) {
                    hideError(textField);
                }
            });
        }

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        okButton = new JButton("确定");
        cancelButton = new JButton("取消");
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        // 添加事件监听器
        okButton.addActionListener(e -> {
            if (validateInputs()) {
                isOkPressed = true;
                dispose();
            }
        });

        cancelButton.addActionListener(e -> dispose());

        // 添加键盘事件监听器
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (validateInputs()) {
                        isOkPressed = true;
                        dispose();
                    }
                } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    dispose();
                }
            }
        });

        // 为输入框添加键盘事件监听器，确保在输入框中也能响应按键
        for (JTextField textField : textFields) {
            textField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        if (validateInputs()) {
                            isOkPressed = true;
                            dispose();
                        }
                    } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        dispose();
                    }
                }
            });
        }

        // 添加面板到对话框
        add(inputPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();

        // 设置对话框的大小
        if (size != null) {
            setSize(size);
        }

        setLocationRelativeTo(parent);
    }

    // 找到组件所在的最顶层 Frame
    private static Frame findFrameForComponent(Component component) {
        while (component != null && !(component instanceof Frame)) {
            component = component.getParent();
        }
        return (Frame) component;
    }

    // 显示错误提示，标红输入框并抖动
    private void showError(JTextField textField) {
        textField.setBorder(BorderFactory.createLineBorder(Color.RED));
        JLabel errorLabel = errorLabels.get(textField);
        errorLabel.setVisible(true);
        shakeTextField(textField);
    }

    // 隐藏错误提示
    private void hideError(JTextField textField) {
        textField.setBorder(UIManager.getBorder("TextField.border"));
        JLabel errorLabel = errorLabels.get(textField);
        errorLabel.setVisible(false);
    }

    // 抖动输入框
    private void shakeTextField(JTextField textField) {
        Point originalLocation = textField.getLocation();
        for (int i = 0; i < 5; i++) {
            textField.setLocation(originalLocation.x + (i % 2 == 0? 5 : -5), originalLocation.y);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        textField.setLocation(originalLocation);
    }

    // 验证输入是否满足必填项要求
    private boolean validateInputs() {
        boolean allValid = true;
        for (Map.Entry<JTextField, Boolean> entry : requiredFields.entrySet()) {
            JTextField textField = entry.getKey();
            boolean isRequired = entry.getValue();
            if (isRequired && textField.getText().trim().isEmpty()) {
                showError(textField);
                allValid = false;
            } else {
                hideError(textField);
            }
        }
        return allValid;
    }

    // 获取输入框的值
    public List<String> getInputValues() {
        List<String> values = new ArrayList<>();
        if (isOkPressed) {
            for (JTextField textField : textFields) {
                values.add(textField.getText());
            }
        }
        return values;
    }
}